#-*- coding:utf8 -*-
'''
Created on 2012-7-5

@author: Bise
'''
import config
import time
import cgi
from app.base import BaseHandler
from lib.session import Session
from tornado.web import authenticated

AT_THANKS = 0
AT_NOTHELP = 1
AT_HELP = 2

class AnswerHandler(BaseHandler):
    
    def initialize(self, method = ''):
        self.__method = method
        
    def get(self):
        pass
    
    @authenticated       
    def post(self, args = ''):
        if args == '/vote':
            self.__vote()
        elif args == '/thanks':
            self.__update_attr(AT_THANKS)
        elif args == '/nohelp':
            self.__update_attr(AT_NOTHELP)
        elif args == '/help':
            self.__update_attr(AT_HELP)
        else:
            self.__update_answer()
    
    def __update_answer(self):
        content = cgi.escape(self.get_argument('content', ''), True)
        qid = int(self.get_argument('qid', ''))
        if not content or qid <= 0:
            self.write(u'请输入回答内容')
        else:
            s = Session(self)
            uid = int(s.get('uid'))
            conn = config.getDBConnect()
            try:
                sql = "SELECT `id` FROM `answer` WHERE `id_question` = %d AND `id_user` = %d" % (qid, uid)
                row = conn.get(sql)
                if row <> None:
                    self.write(u'你已经回答过了')
                else:
                    sql = "INSERT INTO `answer` (`id_question`, `id_user`, `content`, `tm_add`) VALUE "\
                          "(%d, %d, '%s', %d)" % (qid, uid, content, time.time())
                    if conn.execute(sql):
                        sql = "UPDATE `question` SET `cnt_answer` = `cnt_answer` + 1 WHERE `id` = %d" % qid
                        conn.execute(sql)
                    self.write(u'回答成功')
                    url = "/question/%d" % qid
                    self.redirect(url) 
            except:
                self.write(u'数据操作失败')
                
    def __vote(self):
        aid = int(self.get_argument('aid', ''))
        v = int(self.get_argument('v', ''))
        s = Session(self)
        uid = int(s.get('uid'))
        conn = config.getDBConnect()
        agree = 0
        against = 0
        status = v
        old_status = 0
        try:
            sql = "SELECT `status` FROM `answer_vote` WHERE `id_answer`=%d and "\
                "`id_user`=%d" %(aid, uid)
            row = conn.get(sql)
            if row <> None:
                old_status = row.status
                if row.status == v:
                    status = 0
                sql = "UPDATE `answer_vote` SET `status`=%d WHERE `id_answer`=%d "\
                    "and `id_user`=%d" %(status, aid, uid)
            else:
                sql = "INSERT INTO `answer_vote` (`id_answer`, `id_user`, `status`, `add_time`) "\
                    "VALUES (%d, %d, %d, %d)" %(aid, uid, status, time.time())
            conn.execute(sql)
            
            if v > 0:
                if status == 0:
                    agree = -1;
                else:
                    if old_status == -1:
                        against = -1
                    agree = 1;
            else:
                if status == 0:
                    against = -1
                else:
                    if old_status == 1:
                        agree = -1
                    against = 1
            
            sql = "UPDATE `answer` SET `cnt_agree` = `cnt_agree` + %d, "\
                "`cnt_against` = `cnt_against` + %d where `id`=%d" %(agree, against, aid)
            conn.execute(sql)
            
            sql = "SELECT a.`id_user`, b.`name` FROM `answer_vote` a, `user` b "\
                "WHERE a.`id_answer`=%d and a.`status` = 1 and a.`id_user` = b.`id`"%(aid)
            rows = conn.query(sql)
            
            self.display('answer_vote.html', votes = rows, cnt_agree = len(rows))
        except:
            self.write(u'测试')
    
    def __update_attr(self, type):
        aid = int(self.get_argument('aid', ''))
        s = Session(self)
        uid = int(s.get('uid'))
        conn = config.getDBConnect()
        tmp = type
        if type == AT_HELP:
            tmp = AT_NOTHELP
        sql = "SELECT `status` FROM `answer_attr` WHERE `id_answer`=%d and `id_user`=%d and `type` = %d"%(aid, uid, tmp)
        try:
            row = conn.get(sql)
            if row == None:
                if type == AT_THANKS:
                    sql = "INSERT INTO `answer_attr` (`id_answer`, `id_user`, `type`, `status`, `add_time`) "\
                        "VALUES (%d, %d, %d, %d, %d)" %(aid, uid, type, 1, time.time())
                    conn.execute(sql)
                    sql = "UPDATE `answer` SET `cnt_thanks` = `cnt_thanks` + 1 where `id`=%d" %(aid)
                    conn.execute(sql)
                elif type == AT_NOTHELP:
                    sql = "INSERT INTO `answer_attr` (`id_answer`, `id_user`, `type`, `status`, `add_time`) "\
                        "VALUES (%d, %d, %d, %d, %d)" %(aid, uid, type, 1, time.time())
                    conn.execute(sql)
                    sql = "UPDATE `answer` SET `cnt_uninterested` = `cnt_uninterested` + 1 where `id`=%d" %(aid)
                    conn.execute(sql)
            else:
                if type == AT_HELP:
                    sql = "DELETE FROM `answer_attr` WHERE `id_answer`=%d and `id_user` =%d "\
                        " and  `type`=%d" %(aid, uid, tmp)
                    conn.execute(sql)
                    sql = "UPDATE `answer` SET `cnt_uninterested` = `cnt_uninterested` - 1 where `id`=%d" %(aid)
                    conn.execute(sql)
            self.write(u'__update_attr success')
        except:
            self.write(u'__update_attr false')
        
    
            